package com.zhanghu.backendZray.strategy.notify;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.zhanghu.backendZray.enums.NotifyTypeEnum;
import com.zhanghu.backendZray.pojo.entity.DailyPlan;
import com.zhanghu.backendZray.pojo.entity.NotifySendRecord;
import com.zhanghu.backendZray.pojo.entity.NotifySetting;
import com.zhanghu.backendZray.service.NotifySendRecordService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author ZhangDong
 * @date 2024/8/31 11:59
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class BarkNotifyStrategy implements NotifyStrategy {
    private final NotifySendRecordService notifySendRecordService;

    @Override
    public boolean doNotify(DailyPlan plan, NotifySetting setting) {
        String mail = setting.getMail();
        String barkUrl = setting.getBarkUrl();
        if (StrUtil.isEmpty(barkUrl)) {
            log.error("bark notify, no barkUrl... setting:{}", JSON.toJSONString(setting));
            return false;
        }
        String message = String.format("%s标题: %s 内容: %s", barkUrl, plan.getTitle(), plan.getContent());
        String body = HttpRequest.get(message).execute().body();
        BarkResponse barkResponse = JSON.parseObject(body, BarkResponse.class);
        boolean success = barkResponse.getCode() == 200;
        log.info("mail notify, mail:{}, title:{}, content:{}, result:{}", mail, plan.getTitle(), plan.getContent(), success);
        NotifySendRecord mailSendRecord = new NotifySendRecord();
        mailSendRecord.setUserId(plan.getUserId());
        mailSendRecord.setType(setting.getType());
        mailSendRecord.setBarkUrl(barkUrl);
        mailSendRecord.setTitle(plan.getTitle());
        mailSendRecord.setContent(plan.getContent());
        mailSendRecord.setStatus(success ? (byte) 1 : (byte) 2);
        notifySendRecordService.save(mailSendRecord);
        return success;
    }

    @Override
    public NotifyTypeEnum getNotifyType() {
        return NotifyTypeEnum.BARK;
    }

    /**
     * bark 响应
     * 成功示例：{"code":200,"message":"success","timestamp":1725079141}
     */
    @Data
    static class BarkResponse {
        private Integer code;
        private String message;
        private Long timestamp;
    }
}
